package com.gdssoft.framework.action.system;

/*
 *  捷达世软件（深圳）有限公司 地铁三号线考勤系统 
 *  Copyright (C) 2008-2010 ShenZhen JieDaShi Software Limited Company.
 */
import java.util.Date;
import java.util.List;

import javax.annotation.Resource;

import com.gdssoft.core.Constants;
import com.gdssoft.core.command.QueryFilter;
import com.gdssoft.core.util.BeanUtil;
import com.gdssoft.core.util.ContextUtil;
import com.gdssoft.core.web.action.BaseAction;
import com.gdssoft.framework.model.system.AppUser;
import com.gdssoft.framework.model.system.Department;
import com.gdssoft.framework.service.system.AppUserService;
import com.gdssoft.framework.service.system.DepartmentService;

public class DepartmentAction extends BaseAction {

	private Department department;

	public Department getDepartment() {
		return department;
	}

	public void setDepartment(Department department) {
		this.department = department;
	}

	@Resource
	private DepartmentService departmentService;

	@Resource
	private AppUserService appUserService;

	/**
	 * 按照filter查询并合成统一的json格式字符串返回
	 * @param filter
	 * @return
	 */
	private String getDepJsonStr(QueryFilter filter) {
		filter.addFilter("Q_depId_L_GT", "0");
		List<Department> list = departmentService.getAll(filter);

		StringBuffer buff = new StringBuffer("{success:true,'totalCounts':")
				.append(filter.getPagingBean().getTotalItems()).append(
						",result:[");
		for (Department dep : list) {
			buff.append(getDepJsonStr(dep) + ",");
		}
		if (list.size() > 0) {
			buff.deleteCharAt(buff.length() - 1);
		}
		buff.append("]}");
		return buff.toString();
	}

	/**
	 * 查询<b>某节点及其下</b>所有中符合条件的Department
	 * 最多只能到自己能查的最大范围
	 * @author F3229233
	 * @return
	 */
	public String select() {
		boolean success = true;
		
		String curPath = ContextUtil.getCurrentUser().getEmployee().getDepartment().getPath();
		if (department!=null && department.getDepId() != null ) {
			String path = departmentService.get(department.getDepId()).getPath();
			//用path来控制访问权限，防止查询其他管理处数据
			
			//path.startsWith(curPath) path是curPath的子项
			if(path == null || path.startsWith(curPath)){//容错：超级管理员时curPath==null
				curPath = path;	//传入的department.id为合法值使用。
			}else{
				success = false;//传入的department.id为非法值报错。
			}
		}
		
		if(success){	//无传入department.id，返回当前用户范围的全部
			QueryFilter filter = new QueryFilter(getRequest());
			filter.addFilter("Q_path_S_LFK", curPath);		
			jsonString = getDepJsonStr(filter);
		}else{
			jsonString = "{success:false}";
		}
				
		return SUCCESS;
	}

	/**
	 * 按request条件查找符合条件的任何Department列表(不含已删除)
	 * @author F3229233
	 */
	public String list() {
		QueryFilter filter = new QueryFilter(getRequest());
		
		jsonString = getDepJsonStr(filter);
		return SUCCESS;
	}

	public String save() {
		boolean success = true;
		AppUser au = ContextUtil.getCurrentUser();
		Date now = new Date();

		department.setUpdateBy(au.getUsername());
		department.setUpdateDate(now);
		department.setDepLevel(1); // company
		if ("office".equals(getRequest().getParameter("type"))) {
			department.setDepDesc(getConcattedDesc());
			department.setDepLevel(2); // office
		}

		if (department.getDepId() == null) {
			department.setCreateBy(au.getUsername());
			department.setCreateDate(now);
			department.setDelflag(Constants.FLAG_UNDELETED);
		} else {
			Department orgdepartment = departmentService.get(department
					.getDepId());
			try {
				BeanUtil.copyNotNullProperties(orgdepartment, department);
				department = orgdepartment;
			} catch (Exception ex) {
				success = false;
				logger.error(ex.getMessage());
			}
		}

		// 更新department的path
		try {
			department = departmentService.save(department);
			department.setPath(departmentService.get(department.getParentId()).getPath() + department.getDepId() + ".");
			departmentService.save(department);
		} catch (Exception e) {
			success = false;
			logger.error(e.getMessage());
		}

		setJsonString("{success:" + success + "}");
		return SUCCESS;
	}

	public String del() {
		boolean success = true;
		String msg = "";
		if (department.getDepId() == null) {
			msg = "请刷新后重试。";
		} else {
			Department dep = departmentService.get(department.getDepId());
			if (dep.getEmployees().size() > 0) {
				msg = "有下属人员，不能删除。";
			} else {
				QueryFilter filter = new QueryFilter(0,2);
				filter.addFilter("Q_parentId_L_EQ", ""+dep.getDepId());
				if (departmentService.getAll(filter).size() > 0) {
					msg = "有下属子公司或管理处，不能删除。";
				} else {
					try {
						dep.setDelflag(Constants.FLAG_DELETED);
						departmentService.save(dep);
					} catch (Exception ex) {
						msg = "请联系管理员。";
						logger.error(ex.getMessage());
					}
				}
			}
		}
		setJsonString("{success:" + success + ",msg:" + msg + "}");
		return SUCCESS;
	}

	/**
	 * //为了不修改框架表结构，这里将一些字段合并一起存入desc
	 * 
	 * @return
	 */
	private String getConcattedDesc() {
		String desc = "";
		String tel = getRequest().getParameter("officeTel");// 26
		String wh = getRequest().getParameter("officeWorkingHours");// 11
		String bs = getRequest().getParameter("officeBoss");// 10
		String add = getRequest().getParameter("officeAddress");// 50
		desc = "T:" + tel + ",W:" + wh + ",B:" + bs + ",A:" + add;
		logger.debug(">>>>>>>>>>desc:" + desc);
		return desc;
	}

	/**
	 * 分解和并的字段并合成json格式字符串
	 * 
	 * @param dep
	 * @return
	 */
	private String getDepJsonStr(Department dep) {
		StringBuffer buff = new StringBuffer();
		buff.append("{depId:" + dep.getDepId());
		buff.append(",depCode:'" + dep.getDepCode());
		buff.append("',depName:'" + dep.getDepName() + "',");

		// "T:"+tel+",W:"+wh+",B:"+bs+",A:"+add;
		String desc = dep.getDepDesc();
		if (dep.getDepLevel() == 2) {
			desc = desc.replace("T:", "'officeTel':'")
					.replace(",W:", "','officeWorkingHours':'")
					.replace(",B:", "','officeBoss':'")
					.replace(",A:", "','officeAddress':'").concat("'");
		} else {
			desc = "depDesc:'" + desc + "'";
		}
		logger.debug(">>>>>>>>>>desc:" + desc);
		buff.append(desc + "}");

		logger.debug(buff.toString());
		return buff.toString();
	}

	public String get() {
		Long depId = Long.parseLong(getRequest().getParameter("depId"));
		Department department = departmentService.get(depId);

		// 将数据转成JSON格式
		StringBuffer sb = new StringBuffer("{success:true,data:");
		sb.append(getDepJsonStr(department));
		sb.append("}");
		setJsonString(sb.toString());
		return SUCCESS;
	}

	/**
	 * 获取公司树 ，参数all="true"时查询结果包含管理处,否则只查公司
	 * 
	 * @return
	 */
	public String treeByLevel() {
		String levelStr = getRequest().getParameter("all");
		Integer level = "true".equals(levelStr) ? null : 1; // 0:保留，1:公司，2:管理处

		StringBuffer buff = new StringBuffer("[");
		Long parentId = -1L;
		AppUser au = ContextUtil.getCurrentUser();
		if (appUserService.hasRole(au, "ROLE_SUPER")) { // super
			parentId = 1L;
		} else {
			parentId = au.getDepId();
		}

		Department thisdep = departmentService.get(parentId);
		if (thisdep != null) {
			buff.append("{id:'" + thisdep.getDepId() + "',text:'"
					+ thisdep.getDepName() + "',code:'" + thisdep.getDepCode()
					+ "',");
			buff.append(findChild(thisdep.getDepId(), level));
		} else {
			List<Department> listParent = departmentService.findByParentId(
					parentId, level, null);
			for (Department dep : listParent) {
				buff.append("{id:'" + dep.getDepId() + "',text:'"
						+ dep.getDepName() + "',code:'" + dep.getDepCode()
						+ "',");
				buff.append(findChild(dep.getDepId(), level));
			}
		}

		if (buff.length() > 1) {
			buff.deleteCharAt(buff.length() - 1);
		}
		buff.append("]");
		setJsonString(buff.toString());

		return SUCCESS;
	}

	/**
	 * 寻找子根节点，不包括管理处
	 */
	public String findChild(Long depId, Integer level) {
		StringBuffer buff1 = new StringBuffer("");
		List<Department> list = departmentService.findByParentId(depId, level,
				null);
		if (list.size() == 0) {
			buff1.append("leaf:true},");
			return buff1.toString();
		} else {
			buff1.append("expanded:true,children:[");
			for (Department dep2 : list) {
				buff1.append("{id:'" + dep2.getDepId() + "',text:'"
						+ dep2.getDepName() + "',code:'" + dep2.getDepCode()
						+ "',");
				buff1.append(findChild(dep2.getDepId(), level));
			}
			buff1.deleteCharAt(buff1.length() - 1);
			buff1.append("]},");
			return buff1.toString();
		}
	}
}
